package com.it.controller;

import com.it.pojo.ClShoppingCar;
import com.it.pojo.LinkFoodCart;
import com.it.pojo.SysFood;
import com.it.service.ClShoppingCarService;
import com.it.service.LinkFoodCartService;
import com.it.service.SysFoodService;
import com.it.utils.ResultData;
import com.mysql.cj.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

/**
 * @Controller 菜品和餐桌关联关系
 *   作用1： 将当前对象的创建交给spring管理
 *   作用2：作为控制层代码的标识
 */
@Controller
public class ClLinkFoodAndCartController {

    private static final Logger logger = LoggerFactory.getLogger(ClLinkFoodAndCartController.class);

    @Autowired    //自动注入(由spring创建当前对象并为属性赋值)
    private LinkFoodCartService linkFoodCartService;

    @Autowired	//自动注入(由spring创建当前对象并为属性赋值)
    private SysFoodService      sysFoodService;

    @Autowired
    private ClShoppingCarService clShoppingCarService;

    /**
     * 1、新增菜品到餐桌
     */
    private LinkFoodCart addLinkFoodToCart(String cartId, String foodId){
        LinkFoodCart link = new LinkFoodCart();
        link.setId(UUID.randomUUID().toString().substring(0, 32));
        link.setCartId(cartId);
        link.setFoodId(foodId);
        link.setPerAmount(1);

        SysFood food = sysFoodService.findById(foodId);
        link.setFoodName(food.getName());
        link.setPerPrice(food.getPrice());
        link.setTotalPerPrice(food.getPrice());

        int i = linkFoodCartService.addOne(link);
        if(i > 0){
            return link;
        }
        return null;
    }

    /**
     * 2.1、修改关联关系（点击按钮时）
     */
    public LinkFoodCart updateLinkFoodToCart(String cartId, String foodId){
        LinkFoodCart link = new LinkFoodCart();

        List<LinkFoodCart> list = linkFoodCartService.findByCartIdAndFoodId(cartId, foodId);
        if(list != null && list.size() > 0){
            link = list.get(0);
            int nowAmount = link.getPerAmount() + 1;
            link = updateLink(cartId, foodId, nowAmount, link);
        }
        return link;
    }

    /**
     * 2.2、修改关联关系（更改数量时）
     */
    public LinkFoodCart updateLinkFoodToCart(String cartId, String foodId, int nowAmount){
        LinkFoodCart link = new LinkFoodCart();

        List<LinkFoodCart> list = linkFoodCartService.findByCartIdAndFoodId(cartId, foodId);
        if(list != null && list.size() > 0){
            link = list.get(0);
            link = updateLink(cartId, foodId, nowAmount, link);
        }
        return link;
    }

    private LinkFoodCart updateLink(String cartId, String foodId, int nowAmount, LinkFoodCart link){
        link.setPerAmount(nowAmount);
        SysFood food = sysFoodService.findById(foodId);
        link.setFoodName(food.getName());
        Double nowTotalPrice = food.getPrice() * nowAmount;
        link.setTotalPerPrice(nowTotalPrice);

        int i = linkFoodCartService.updateOne(link);
        if(i > 0){
            return link;
        }
        return null;
    }


    /**
     * 3、删除关联关系
     */
    public int deleteLinkFoodToCart(String cartId, String foodId){
        int i = 0;
        List<LinkFoodCart> list = linkFoodCartService.findByCartIdAndFoodId(cartId, foodId);
        if(list != null && list.size() > 0){
            for(LinkFoodCart link:list){
                i = linkFoodCartService.deleteOne(link.getId());
            }
        }
        return i;
    }

    /**
     *  4、执行刷新购物车操作
     *
     * 		 * 1、获取客户id，查看客户是否有购物车，没有则创建并返回cartId；
     * 		 * 2、获取要添加到 餐桌的菜品主键foodId
     * 		 * 3、根据cartId和foodId查询是否已经在餐桌里加入了该菜品/套餐
     * 		 * 4、没有则新增，有则数量+1
     * 		 * 5、重新查询购物车和关联关系，刷新页面的购物车列表（前台执行） 刷新session中loginUser的购物车信息（后台执行）
     *
     */
    @RequestMapping("/freshCartInfo")
    @ResponseBody
    public ResultData<ClShoppingCar> freshCartInfo(HttpServletRequest request, HttpServletResponse response){
        try{
            String addFoodId = (String) request.getParameter("addFoodId");
            String updateFoodId = (String) request.getParameter("updateFoodId");
            int updateFoodAmount = 0;
            if(request.getParameter("updateFoodAmount") != null && !StringUtils.isNullOrEmpty(request.getParameter("updateFoodAmount").toString())){
                updateFoodAmount = Integer.parseInt(request.getParameter("updateFoodAmount").toString());
                if(updateFoodAmount == 0){
                    updateFoodAmount = 1;
                }
            }
            String delFoodId = (String) request.getParameter("delFoodId");

            ResultData<ClShoppingCar> resultData = new ResultData<ClShoppingCar>();
            HttpSession session = request.getSession();
            String loginUserId = (String) session.getAttribute("loginUserId");
            String loginUserName = (String) session.getAttribute("loginUserName");

            /**
             * 1、获取客户id，查看客户是否有购物车，没有则创建并返回cartId；
             */
            List<ClShoppingCar> carts = clShoppingCarService.findByUserId(loginUserId);
            ClShoppingCar cart = new ClShoppingCar();
            if(carts != null && carts.size() > 0){
                /**
                 * 有就直接用
                 */
                cart = carts.get(0);
            }else{
                /**
                 * 没有就新增
                 */
                cart.setId(UUID.randomUUID().toString().substring(0, 32));
                cart.setUserId(loginUserId);
                cart.setUserName(loginUserName);
                clShoppingCarService.addClShoppingCar(cart);
            }

            /**
             * 2.1、获取要添加到 餐桌的菜品主键foodId
             */
            String foodIds = "";
            if(!StringUtils.isNullOrEmpty(addFoodId)){

                /**
                 * 3、根据cartId和foodId查询是否已经在餐桌里加入了该菜品/套餐
                 */
                foodIds = (String) session.getAttribute("foodIds");
                int indexOf = foodIds.indexOf(addFoodId+",");
                /**
                 * 4、没有则新增菜品到餐桌，有则数量+1
                 */
                if(indexOf > -1){
                    /**
                     * 已有，则修改
                     */
                    updateLinkFoodToCart(cart.getId(), addFoodId);
                }else{
                    /**
                     * 没有则新增
                     */
                    addLinkFoodToCart(cart.getId(), addFoodId);
                }
            }

            /**
             * 2.2、获取要修改数量的菜品主键foodId和foodAmount
             */
            if(!StringUtils.isNullOrEmpty(updateFoodId) && updateFoodAmount != 0){
                updateLinkFoodToCart(cart.getId(), updateFoodId, updateFoodAmount);
            }

            /**
             * 2.3、获取要删除掉的 餐桌的菜品主键foodId
             */
            if(!StringUtils.isNullOrEmpty(delFoodId)){
                deleteLinkFoodToCart(cart.getId(), delFoodId);
            }

            /**
             * 5、重新查询购物车和关联关系，刷新页面的购物车列表（前台执行） 刷新session中loginUser的购物车信息（后台执行）
             */
            String linkFoodCartIds = "";
            List<LinkFoodCart> linkList = linkFoodCartService.findByCartId(cart.getId());

            int foodCountTotal = 0;
            double foodPriceTotal = 0.00;
            for(LinkFoodCart link:linkList){
                foodIds += link.getFoodId() + ", ";
                linkFoodCartIds += link.getId() + ", ";
                foodCountTotal += link.getPerAmount();
                link.setTotalPerPrice(link.getPerPrice()*link.getPerAmount());
                foodPriceTotal += link.getTotalPerPrice();
            }
            cart.setLinkFoodCarts(linkList);
            cart.setFoodCountTotal(foodCountTotal);
            cart.setFoodPriceTotal(foodPriceTotal);
            clShoppingCarService.updateById(cart);

            resultData.setCode(200);
            resultData.setData(cart);
            resultData.setMsg("刷新餐桌成功！");
            resultData.setSuccess(true);

            /**
             * session更新
             */
            session.setAttribute("cartId", cart.getId());
            session.setAttribute("foodIds", foodIds);
            session.setAttribute("linkFoodCartIds", linkFoodCartIds);

            return resultData;
        }catch (RuntimeException re){
            re.printStackTrace();
        }
        return null;
    }

}
